import axios, { AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios';

const instance = axios.create({
  baseURL: 'http://localhost:3000/api',
  timeout: 10000,
});

instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    if (config.data instanceof FormData) {
        delete config.headers['Content-Type'];
    } else if (!config.headers['Content-Type']) {
        config.headers['Content-Type'] = 'application/json';
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      console.error("Unauthorized, redirecting to login...");
    }
    return Promise.reject(error.response?.data?.error || error.message);
  }
);


export const get = (url: string, params?: object) => instance.get(url, { params });
export const post = (url: string, data: any, config?: AxiosRequestConfig) => instance.post(url, data, config);
export const put = (url: string, data: any) => instance.put(url, data);
export const del = (url: string) => instance.delete(url);

export default instance;